import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'profile_page_controller.dart';
import '../../function/model/post_model.dart';
import '../../function/utils/my_common.dart';

/// 个人资料页面组件
/// 使用非常规命名避免标准模式
class ProfilePage extends GetView<ProfilePageController> {
  const ProfilePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/communal_bg.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Obx(() {
            if (!controller.isLoggedIn) {
              return _buildNotLoggedInView();
            } else {
              return _buildLoggedInView();
            }
          }),
        ),
      ),
    );
  }

  /// 构建未登录视图
  Widget _buildNotLoggedInView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // Logo
          Container(
            width: 120.w,
            height: 120.w,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(24.r),
              image: const DecorationImage(
                image: AssetImage('assets/images/logo.png'),
                fit: BoxFit.contain,
              ),
              border: Border.all(color: MyCommonUtils.green, width: 3),
            ),
          ),

          SizedBox(height: 40.h),

          // 提示文本
          Text(
            'Welcome to Cult',
            style: TextStyle(
              fontSize: 28.sp,
              fontWeight: FontWeight.bold,
              color: MyCommonUtils.white,
            ),
          ),

          SizedBox(height: 16.h),

          Text(
            'Please login to view your profile and manage your posts',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 16.sp,
              color: MyCommonUtils.white.withOpacity(0.8),
              height: 1.4,
            ),
          ),

          SizedBox(height: 50.h),

          // 前往登录按钮
          Container(
            width: 200.w,
            height: 50.h,
            child: ElevatedButton(
              onPressed: controller.goToLogin,
              style: ElevatedButton.styleFrom(
                backgroundColor: MyCommonUtils.green,
                foregroundColor: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.r),
                ),
                elevation: 0,
              ),
              child: Text(
                'Go to Login',
                style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.w600),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建已登录视图
  Widget _buildLoggedInView() {
    return Column(
      children: [
        // 顶部设置按钮
        _buildTopBar(),

        // 可滚动的内容区域
        Expanded(
          child: SingleChildScrollView(
            child: Column(
              children: [
                // 用户信息区域
                _buildUserInfoSection(),

                // 统计信息
                _buildStatsSection(),

                // 标签页
                _buildTabSection(),

                // 时间线内容
                _buildTimelineContent(),

                SizedBox(height: 100.h),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 构建顶部栏
  Widget _buildTopBar() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 0.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          // 设置按钮
          Image.asset(
            'assets/images/setting.png',
            width: 24.w,
            height: 24.w,
          ).inkWell(onTap: controller.goToSettings),
        ],
      ),
    );
  }

  /// 构建用户信息区域
  Widget _buildUserInfoSection() {
    final user = controller.currentUser!;

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 20.h),
      child: Column(
        children: [
          // 用户头像
          CircleAvatar(radius: 50.w, backgroundImage: AssetImage(user.avatar)),

          SizedBox(height: 16.h),

          // 用户名
          Text(
            user.nickname.isNotEmpty ? user.nickname : user.username,
            style: TextStyle(
              fontSize: 24.sp,
              fontWeight: FontWeight.bold,
              color: MyCommonUtils.white,
            ),
          ),

          SizedBox(height: 8.h),

          // 用户签名
          Text(
            user.signature.isNotEmpty
                ? user.signature
                : 'Plant lover and nature enthusiast',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 14.sp,
              color: MyCommonUtils.white.withOpacity(0.8),
              height: 1.4,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建统计信息区域
  Widget _buildStatsSection() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          _buildStatItem('Following', controller.followingCount),
          _buildStatDivider(),
          _buildStatItem('Followers', controller.followersCount),
          _buildStatDivider(),
          _buildStatItem('Likes', controller.likesReceivedCount),
        ],
      ),
    );
  }

  /// 构建统计项
  Widget _buildStatItem(String label, int count) {
    return Column(
      children: [
        Text(
          count.toString(),
          style: TextStyle(
            fontSize: 20.sp,
            fontWeight: FontWeight.bold,
            color: MyCommonUtils.white,
          ),
        ),
        SizedBox(height: 4.h),
        Text(
          label,
          style: TextStyle(
            fontSize: 12.sp,
            color: MyCommonUtils.white.withOpacity(0.8),
          ),
        ),
      ],
    ).inkWell(
      onTap: () {
        if (label == 'Following') {
          controller.goToFollowingList();
        } else if (label == 'Followers') {
          controller.goToFollowersList();
        }
      },
    );
  }

  /// 构建统计项分隔符
  Widget _buildStatDivider() {
    return Container(
      width: 1.w,
      height: 40.h,
      color: Colors.white.withOpacity(0.3),
    );
  }

  /// 构建标签页区域
  Widget _buildTabSection() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20.w, vertical: 20.h),
      decoration: BoxDecoration(
        color: Colors.white.withValues(alpha: 0.2),
        borderRadius: BorderRadius.circular(100.r),
      ),
      child: Row(
        children: [
          Expanded(child: _buildTabButton('Posts', 0)),
          Expanded(child: _buildTabButton('Favorites', 1)),
        ],
      ),
    );
  }

  /// 构建标签按钮
  Widget _buildTabButton(String label, int index) {
    return Obx(() {
      final isSelected = controller.currentTabIndex.value == index;
      return Container(
        padding: EdgeInsets.symmetric(vertical: 10.h),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment(0.00, 1.00),
            end: Alignment(1.01, -0.00),
            colors: [
              isSelected ? Color(0xFFFF8D00) : Colors.transparent,
              isSelected ? Color(0xFF00FFB2) : Colors.transparent,
            ],
          ),
          borderRadius: BorderRadius.circular(100.r),
        ),
        child: Text(
          label,
          textAlign: TextAlign.center,
          style: TextStyle(
            fontSize: 24.sp,
            fontWeight: isSelected ? FontWeight.w700 : FontWeight.w400,
            color: Colors.white,
          ),
        ),
      ).inkWell(onTap: () => controller.switchTab(index));
    });
  }

  /// 构建时间线内容
  Widget _buildTimelineContent() {
    return Obx(() {
      if (controller.currentTabIndex.value == 0) {
        return _buildPostsTimeline();
      } else {
        return _buildFavoritesTimeline();
      }
    });
  }

  /// 构建帖子时间线
  Widget _buildPostsTimeline() {
    final postsByDate = controller.userPostsByDate;

    if (postsByDate.isEmpty) {
      return Container(
        height: 200.h,
        child: Center(
          child: Text(
            'No posts yet',
            style: TextStyle(
              fontSize: 16.sp,
              color: MyCommonUtils.white.withOpacity(0.7),
            ),
          ),
        ),
      );
    }

    return Container(
      margin: EdgeInsets.only(left: 20.w, right: 20.w),
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: Colors.white.withValues(alpha: 0.12),
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(color: Colors.white.withOpacity(0.2), width: 1),
      ),
      child: _buildConnectedTimeline(postsByDate),
    );
  }

  /// 构建收藏时间线
  Widget _buildFavoritesTimeline() {
    final postsByDate = controller.userLikedPostsByDate;

    if (postsByDate.isEmpty) {
      return Container(
        height: 200.h,
        child: Center(
          child: Text(
            'No favorites yet',
            style: TextStyle(
              fontSize: 16.sp,
              color: MyCommonUtils.white.withOpacity(0.7),
            ),
          ),
        ),
      );
    }

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20.w, vertical: 0.h),
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: Colors.white.withValues(alpha: 0.12),
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(color: Colors.white.withOpacity(0.2), width: 1),
      ),
      child: _buildConnectedTimeline(postsByDate),
    );
  }

  /// 构建简化的时间线
  Widget _buildConnectedTimeline(Map<String, List<PostModel>> postsByDate) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 按日期分组显示内容
        ...postsByDate.entries.toList().asMap().entries.map((dateGroupEntry) {
          final dateEntry = dateGroupEntry.value;
          final date = dateEntry.key;
          final posts = dateEntry.value;

          return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 日期标题
              Container(
                margin: EdgeInsets.only(bottom: 16.h),
                child: Text(
                  date,
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.bold,
                    color: MyCommonUtils.white,
                    letterSpacing: 0.5,
                  ),
                ),
              ),

              // 该日期的所有帖子
              ...posts.map((post) => _buildTimelineItemContent(post)).toList(),

              SizedBox(height: 24.h),
            ],
          );
        }).toList(),
      ],
    );
  }

  /// 构建时间线项目内容
  Widget _buildTimelineItemContent(PostModel post) {
    return Container(
      margin: EdgeInsets.only(bottom: 24.h),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 时间显示区域
          Container(
            width: 50.w,
            padding: EdgeInsets.only(top: 2.h),
            child: Text(
              controller.formatTime(post.publishTime),
              style: TextStyle(
                fontSize: 12.sp,
                color: MyCommonUtils.white.withOpacity(0.7),
                fontWeight: FontWeight.w500,
              ),
            ),
          ),

          SizedBox(width: 12.w),

          // 帖子内容
          Expanded(child: _buildPostItem(post)),
        ],
      ),
    );
  }

  /// 构建帖子项
  Widget _buildPostItem(PostModel post) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 帖子内容区域
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 帖子标题
            Text(
              post.title,
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.bold,
                color: MyCommonUtils.white,
                height: 1.2,
              ),
            ),

            SizedBox(height: 12.h),

            // 帖子内容
            Text(
              post.content,
              style: TextStyle(
                fontSize: 15.sp,
                color: MyCommonUtils.white.withOpacity(0.9),
                height: 1.5,
              ),
            ),

            SizedBox(height: 16.h),

            // 帖子标签
            if (post.tags.isNotEmpty)
              Wrap(
                spacing: 8.w,
                runSpacing: 6.h,
                children:
                    post.tags.take(3).map((tag) {
                      return Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 12.w,
                          vertical: 6.h,
                        ),
                        decoration: BoxDecoration(
                          color: MyCommonUtils.white.withOpacity(0.15),
                          borderRadius: BorderRadius.circular(16.r),
                          border: Border.all(
                            color: MyCommonUtils.white.withOpacity(0.3),
                            width: 1,
                          ),
                        ),
                        child: Text(
                          '# $tag',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: MyCommonUtils.white.withOpacity(0.8),
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      );
                    }).toList(),
              ),

            SizedBox(height: 16.h),
          ],
        ),

        // 帖子图片/视频
        if (post.resourceType == ResourceType.image)
          _buildPostImage(post)
        else if (post.resourceType == ResourceType.video)
          _buildPostVideo(post),
      ],
    ).inkWell(onTap: () => controller.goToPostDetail(post));
  }

  /// 构建帖子图片
  Widget _buildPostImage(PostModel post) {
    return ClipRRect(
      borderRadius: BorderRadius.all(Radius.circular(16.r)),
      child: Image.asset(
        post.resourcePath,
        width: double.infinity,
        height: 220.h,
        fit: BoxFit.cover,
      ),
    );
  }

  /// 构建帖子视频
  Widget _buildPostVideo(PostModel post) {
    return GestureDetector(
      onTap: () => controller.playVideo(post),
      child: Stack(
        children: [
          ClipRRect(
            borderRadius: BorderRadius.all(Radius.circular(16.r)),
            child: Image.asset(
              post.coverImagePath ?? post.resourcePath,
              width: double.infinity,
              height: 220.h,
              fit: BoxFit.cover,
            ),
          ),
          // 播放按钮
          Positioned.fill(
            child: Center(
              child: Container(
                width: 70.w,
                height: 70.w,
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.7),
                  shape: BoxShape.circle,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.3),
                      blurRadius: 8,
                      spreadRadius: 2,
                    ),
                  ],
                ),
                child: Icon(
                  Icons.play_arrow,
                  color: MyCommonUtils.white,
                  size: 35.sp,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
